import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '@/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    refresh_token: localStorage.getItem('refresh_token') || ''
  },
  getters: {
  },
  mutations: {
    SET_TOKEN (state, value) {
      state.token = value
      localStorage.setItem('token', value)
    },
    SET_REFRESH_TOKEN (state, value) {
      state.refresh_token = value
      localStorage.setItem('refresh_token', value)
    },
    CLEAR_ALL (state) {
      state.token = ''
      state.refresh_token = ''
    }
  },
  actions: {
    async getToken (store, value) {
      try {
        const res = await loginAPI(value)
        store.commit('SET_TOKEN', res.data.data.token)
        store.commit('SET_REFRESH_TOKEN', res.data.data.refresh_token)
        return res
      } catch (error) {
        return Promise.reject(error)
      }
    }
  },
  modules: {

  }
})
